package org.zjt.platform.spring.boot.example.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author <a href="juntao.zhang@qq.com">juntao.zhang</a>
 * @Description:
 * @Package org.zjt.platform.spring.boot.example.common
 * @date 2018/3/14 14:00
 * @see
 */
@Configuration
@Slf4j
public class RabbitMQConfig {

    /**
     * 创建队列  rabbitmq-auto
     * @return
     */
    @Bean
    public Queue createAutoQueue() {
        return new Queue("rabbitmq-auto");
    }

    @Bean
    public Queue createManualQueue() {
        return new Queue("rabbitmq-manual");
    }


    /**
     * 定制 RabbitTemplate
     * @param rabbitConnectionFactory
     * @return
     */
    @Bean
    public RabbitTemplate manualRabbitTemplate(CachingConnectionFactory rabbitConnectionFactory){
        //开启发布确认
        rabbitConnectionFactory.setPublisherConfirms(true);
        //返回通知
        rabbitConnectionFactory.setPublisherReturns(true);

        RabbitTemplate rabbitTemplate =new RabbitTemplate(rabbitConnectionFactory);
        //开启确认模式[connectionFactory.setPublisherConfirms(true)],确认消息将被发送到客户端 ConfirmCallback
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> log.info("ConfirmCallback confirm correlationData:{}\t ack:{} \t cause:{} ",correlationData ,ack ,cause));
        rabbitTemplate.setMandatory(true);
        //mandatory属性必须被设定为true.并且，connectionFactory.setPublisherReturns(true);。返回将被发送到客户端ReturnCallback。
        rabbitTemplate.setReturnCallback((message, i, s, s1, s2) -> log.info("ReturnCallback  returnedMessage message :{} \t:{}\t:{}\t:{}\t:{}"+message ,i ,s ,s1,s2));
        return  rabbitTemplate;
    }

}
